#include <stdio.h>

#define MAX_ITEMS 1000;

int insert(char* key, char* data, void* list);
char* search(char* key, void* list);
int delete_item(char* key, void* list);
void* create_list();
int destroy(void* list);

struct list_entry {
	char* key;
	char* data;
	struct list_entry* next;
};

struct list_entry* head;

void* create_list() {
	head = calloc(1, sizeof(struct list_entry));
	head->key = NULL;
	head->next = NULL;
	head->data = NULL;
	return (void*) head;
}

int insert(char* key, char* data, void* list) {
	struct list_entry* current = (struct list_entry*) list;

	//First element
	if (current->key == NULL) {
		current->key = key;
		current->data = data;
		current->next = NULL;
	} else {
		//Go to last element
		while (current->next != NULL) {
			printf("*");
			current = current->next;
		}
		printf("\n");

		//Create new element at the end of the list
		current->next = calloc(1, sizeof(struct list_entry));
		current->next->next = NULL;
		current->next->data = data;
		current->next->key = key;
	}

	printf("Added %s to list\n", key);
	return 1;
}

char* search(char* search_key, void* list) {
	//First element is the list itself
	struct list_entry* current = (struct list_entry*) list;

	//Current key matches the one we are looking, return the data
	while (current != NULL && current->key != NULL) {
		if (strcmp(current->key, search_key) == 0) {
			return current->data;
		}
		current = current->next;
	}

	//If we reach end of the list return NULL;
	return NULL;
}

int delete_item(char* key, void* list) {
	struct list_entry* current = (struct list_entry*) list;

	//First element
	if (current->key != NULL && strcmp(current->key, key) == 0) {
		if (current->next == NULL) {
//			free(current->key);
			current->key = NULL;
			current->next = NULL;
			current->data = NULL;
		} else {
//			free(current->key);
			head->next = head->next->next;
		}
		//free stuff!!!
		return 1;
	}

	do {
		if (current->next->key != NULL && strcmp(current->next->key, key) == 0) {
			if (current->next->next == NULL) {
//				free(current->next->key);
				current->next = NULL;
			} else {
				current->next = current->next->next;
			}
			//free stuff!!!
			return 1;
		}

		current = current->next;
	} while (current->next != NULL);
	return 0;
}

int destroy(void* list) {

	return 0;
}